// pages/queue/queue.js
const _= wx.cloud.database().command
const app = getApp()
// let userId = 'oPAGX5emkFj4gszs2Rv_aqHaopIo'
let openId = getApp().globalData.openid 
Page({
  data: {

  },
  onShow(options) {
    // console.log(this.getTime_Id());
    this.getNum()
    console.log(openId);
  },
  queueLxj(){
    console.log('排号');
    let date = this.getTime_Id()
    // console.log(date);
    // 添加排位数据之前查询是否有数据
    wx.cloud.database().collection('queue')
    .doc(date)
    .get()
    .then(res=>{
      console.log('查询数据：',res);
      if(res.data && res.data._id){
        //有数据则 更新排位数据
        wx.cloud.callFunction({
          name:'queue',
          data:{
            id:this.getTime_Id(),
            action:'user'
          }
        }).then(res=>{
          console.log('openid是',res);
          this.getNum()
        })
      }
    }).catch(res=>{
      wx.cloud.database().collection('queue')
        .add({
          data:{
            _id:date,
            date:this.getTimeYMD(),
            list:[openId],
            num:0
          }
        }).then(res=>{
          console.log('排号添加结果：',res);
          this.getNum()
        }).catch(res=>{
          console.log('排号添加失败！',res);
        })
    })
  },
  // 获取排号列表的_id
  getTime_Id(){
    let d = new Date();
    let month = d.getMonth() + 1 ;
    let date = d.getDate() + '';
    let year = d.getFullYear() + ''  ;
    if(month<=9){
      month = '0' + month
    }
    if(date<=9){
      date = '0' + date
    }
    return year + month + date
  },
  // 获取年月日
  getTimeYMD(){
    let d = new Date();
    let month = d.getMonth() + 1 + '月';
    let date = d.getDate() + '日';
    let year = d.getFullYear() + '年';
    return year + month + date
  } ,
  getNum(){
    wx.cloud.database().collection('queue').doc(this.getTime_Id()).get()
    .then(res=>{
      console.log(res);
      if(res.data && res.data._id){
        let mynum = res.data.list.lastIndexOf(openId) + 1
        console.log('当前用户排号',res.data.list.lastIndexOf(openId) + 1 );
        this.setData({
          mynum,
          num:res.data.num
        })
      }
    })
    .catch(res=>{
      console.log('今日没有排号',res);
    })
  }
})